<!--  -->
<template>
     <div class="zzr_upload_item" :ref="formname" :id="formname" v-loading="loadingInturce" element-loading-text="文件正在上传,请耐心等待，等待期间请勿刷新或关闭页面...">
         <div class="upload_items">
            <div class="item" v-for="(item,index) in fileList" :key="index">
                <div class="item_content">
                    <div class="item_img">
                        <template v-if="matchFileType(item.url) =='image'">
                            <el-image class="i_r_img" :src="item.url" fit="contain"></el-image>
                        </template>
                        <template v-else>
                            <img class="i_icon" :src="require(`@/assets/icon/icon_${matchFileType(item.url)}2@2x.png`)" :alt="matchFileType(item.url)">
                            <div class="name">{{item.name}}</div>
                        </template>
                    </div>
                    <span class="item_handles">
                        <span class="item_handle item_handle_view" @click="handlePictureCardPreview(index)"><i class="el-icon-zoom-in"></i></span>
                        <span class="item_handle item_handle_delete" v-if="!viewOnly" @click="handleRemove(index)"><i class="el-icon-delete"></i></span>
                    </span>
                </div>
             </div>
            <el-upload
                class="item"
                :action="uploadUrl"
                :file-list="fileList"
                :on-success="changeFileList"
                :show-file-list="false"
                name="pic"
                :on-progress="onPorgress"
                :data="data"
                :limit="limit"
                :on-exceed="handleExceed"
                v-if="!viewOnly && limit>fileList.length"
            >
                <div class="item_content item_upload">
                    <i class="el-icon-plus"></i>
                    <div>{{$t('message.chooseFile')}}</div>
                </div>
            </el-upload>
         </div>
     </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import filetype from '@/utils/fileTypeMatch'
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props:{
      value:[String,Number],
      list:{
          type:String,
          default:''
      },
      fileCode:{
          type:[String,Number],
          default:'0'
      },
      imgUrl:String,
      viewOnly:{
          type:Boolean,
          default:false
      },
      limit:[String,Number]
      ,
      data:{}
  },
  data() {
    //这里存放数据
    return {
        propValue:'',
        loadingInturce:false,
        uploadUrl:process.env.NODE_ENV=='development'?'/api/common/savePics':this.uploadUrl,
        fileList:[]
    };
  },
  //监听属性 类似于data概念
  computed: {
      formname(){
          return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
      }
  },
  //监控data中的数据变化
  watch: {
      fileList(newArray){

          let sting = '',codeArr = [];
          newArray.forEach((item,index)=>{
              codeArr.push({mtype:this.fileCode,pic:item.picname,fjname:item.name,id:item.id,url:item.url})
          })
        this.$emit('input',JSON.stringify(codeArr))
      },
      value:{
          handler(newval,oldval){
              this.getPropValue(newval)
          },
          deep:true
      }
  },
  //方法集合
  methods: {
      onPorgress(event, file, fileList) {
        this.loadingInturce = true
      },
      changeFileList(response, file, fileList){
          this.loadingInturce = false;
          if(response.code==0){
            let data = response.zzrresult.pic[0];
            this.fileList.push({
                name:data.filename,
                picname:data.picname,
                url:data.webpath,
                id:''
            });
          }else{
            this.$message({message:response.message,type:'error'})
          }
      },
      getPropValue(val){
        if(val!=='' && val!==null){

            let fileList = JSON.parse(val),
            newList = [];
            fileList.forEach((item,index)=>{
                newList.push({name:item.fjname,id:item.id,url:item.url && item.url.indexOf('http')>-1 ? item.url : this.imgUrl+item.pic,picname:item.pic})
            });
            this.fileList = newList;
        }
      },
      matchFileType(filename){
          return filetype.fileTypeMatch(filename);
      },
      handleRemove(index){
        let that = this;
        that.$confirm(that.$t('message.delateThisConfirm'), that.$t('message.tips'), {
            type: 'info',
            callback: action => {
                if (action === 'confirm') {
                    that.fileList.splice(index,1)
                }
            }
        })
      },
      handlePictureCardPreview(index){
        window.open(this.fileList[index].url)
      },
    handleExceed(files, fileList) {
      this.$message.warning(this.$t("message.pdftip")+this.limit+this.$t("message.pdftips"));
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.propValue = this.value;
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='stylus' scoped>

//@import url(); 引入公共css类
.zzr_upload_item
    position relative
    .upload_items
        display flex
        flex-wrap wrap
        .item
            position relative
            .item_content
                width 110px
                height 110px
                margin 5px
                position relative
                overflow hidden
                border-radius 4px
                border 1px dashed $gray
                .item_img
                    width 100%
                    height 100%
                    box-sizing border-box
                    position relative
                    .i_r_img
                        width 100%
                        height 100%
                    .i_icon
                        width 50px
                        height 50px
                        margin 10px auto 5px
                        display block
                    .name
                        font-size $miniSize
                        text-align center
                        padding 0 5px
                        display -webkit-box
                        -webkit-box-orient vertical
                        -webkit-line-clamp 2
                        height 40px
                        line-height 20px
                        overflow hidden
                        text-overflow ellipsis
                        word-break break-all
                .item_handles
                    position absolute
                    width 100%
                    height 100%
                    left 0
                    top 0
                    cursor pointer
                    text-align center
                    color #fff
                    background-color rgba(0,0,0,.5)
                    opacity 0
                    transition all .3s ease-in-out
                    .item_handle
                        &::after
                            display inline-block
                            content ''
                            height 100%
                            vertical-align middle
                        &>[class*='el-icon']
                            font-size 20px
                            margin 5px
            &:hover .item_handles
                opacity 1
            .item_upload
                background $shallowGray
                display flex
                justify-content center
                flex-direction column
                color $gray
                i
                    font-size 20px
                &:hover
                    border-color $colorBle
                    color $colorBle
</style>
